﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodePlex.TfsPluginSuite.Configuration;
using CodePlex.TfsPluginSuite.Helper;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Server;

namespace CodePlex.TfsPluginSuite.Overrides
{
    public class AccountOverride : ISubscriber
    {
        public string Name
        {
            get { return "CodePlex.TfsPluginSuite.Overrides.AccountOverride"; }
        }

        public SubscriberPriority Priority
        {
            get { return SubscriberPriority.High; }
        }

        public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {
            properties = new ExceptionPropertyCollection();
            statusMessage = String.Empty;
            statusCode = 0;

            // If this is a check-in notification and is a decision point
            if (notificationEventArgs is CheckinNotification && notificationType == NotificationType.DecisionPoint)
            {
                // run if enabled
                var config = TfsPluginSuiteConfigurationManager.Section.AccountOverride;
                if (config.Enabled)
                {
                    CheckinNotification notification = notificationEventArgs as CheckinNotification;

                    using (var tfsHelper = new TfsHelper(requestContext, notification))
                    {
                        foreach (AccountOverrideConfigElement group in config)
                        {
                            string groupName = group.Name.Replace("@ProjectCollection", requestContext.ServiceHost.Name);
                            if (tfsHelper.IsInGroup(groupName, notification.ChangesetOwner.Descriptor))
                            {
                                return EventNotificationStatus.ActionApproved;
                            }
                        }
                    }
                }
            }
            return EventNotificationStatus.ActionPermitted;
        }

        public Type[] SubscribedTypes()
        {
            return new Type[] { typeof(CheckinNotification) };
        }
    }
}